/**
 * 
 */
package edu.hawaii.duedates.library;

import java.net.UnknownHostException;
import com.meterware.httpunit.GetMethodWebRequest;
import com.meterware.httpunit.HttpUnitOptions;
import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.WebForm;
import com.meterware.httpunit.WebRequest;
import com.meterware.httpunit.WebResponse;
import com.meterware.httpunit.WebTable;

/**
 * This class is built for actions related to the UH Manoa Library system.
 * It is also implements the Lender interface.  Must have login and getInfo.
 * 
 * @author John Ly
 * @author John Zhou
 */
public class UhManoa extends Lender {

  /**
   * Attempts to login to UH Manoa Library system.
   * 
   * @param id The UH user ID.
   * @param lastName The UH user's last name.
   * @return The WebConversation instance after successful login.
   * @throws Exception If login was not successful with these credentials.
   */
  public WebConversation login(String id, String lastName) throws Exception {
    String url = "http://uhmanoa.lib.hawaii.edu/cgi-bin/Pwebrecon.cgi?DB=local&PAGE=pbLogon";
    // UH Library website has bogus JavaScript code.
    HttpUnitOptions.setExceptionsThrownOnScriptError(false);
    // create the conversation object which will maintain state for us
    WebConversation conversation = new WebConversation();
    WebRequest request = new GetMethodWebRequest(url);
    WebResponse response = conversation.getResponse(request);
    WebForm form = response.getFormWithName("logonpage");
    form.setParameter("BC", id);
    form.setParameter("LN", lastName);
    form.submit();
    response = conversation.getCurrentPage();
    if (response.getText().contains("Sorry, Login unsuccessful")) {
      throw new Exception("Error while logging in to UH Library");
    }
    return conversation;
  }  
  
  /**
   * Given a logged in user to the UH Library site, provides info about their library books.
   * 
   * @param id The UH user ID.
   * @param lastName The UH user's last name.
   * @return A String containing information about their books.
   * @throws Exception If problems occur parsing the site pages.
   */
  public String getInfo(String id, String lastName) throws Exception {
    String uhSiteNoItemString = "You have no items checked out.";
    try {
      WebConversation conversation = this.login(id, lastName);
      WebResponse response = conversation.getCurrentPage();
      WebForm form = response.getForms()[0];
      if (uhSiteNoItemString.equals(form.getText())) {
        return "No books checked out";
      }
      else {
        // Assume the "Checked Out Items" table contains "Renew"
        WebTable table = response.getTableStartingWith("Renew?");        
        String checkOutInfo = this.toFormattedString("Due Date", "Book Title");
        String dueDate = "";
        String bookTitle = "";
        for (int i = 1; i < table.getRowCount(); i++) {
          dueDate = table.getCellAsText(i,3);
          bookTitle = table.getCellAsText(i,1);
          checkOutInfo = checkOutInfo.concat(toFormattedString(dueDate, bookTitle));
        }
        return checkOutInfo;
      }
    }
    catch (Exception e) {
      if (e.getCause() instanceof UnknownHostException) {                
        return " Error logging in (Connection to library could not be made";
      }
      else {
        return " Error logging in (Please check your arguments: UH <id> <lastname>";
      }
     //throw new Exception("Error getting UH Book info", e);
    }
  }

}
